package com.good.app.guide

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.util.AttributeSet
import android.view.Gravity
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import com.good.app.R
import com.good.app.util.DensityUtils
import java.util.ArrayList

class CustomIndicator : LinearLayout {

    private var mSum = 1
    private var mSelected = 0
    private var mContext: Context? = null
    private val imageViewList = ArrayList<ImageView>()
    private var mLayoutParams: LinearLayout.LayoutParams? = null
    private var padding = 25
    private var indicatorRes =
        intArrayOf(R.mipmap.horizontal_line, R.mipmap.horizontal_line_gray)

    fun setPadding(padding: Int) {
        this.padding = padding
    }

    fun setIndicatorRes(indicatorRes: IntArray) {
        this.indicatorRes = indicatorRes
    }

    constructor(context: Context) : super(context) {
        this.mContext = context
        init()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        this.mContext = context
        init()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        this.mContext = context
        init()
    }

    private fun init() {
        setBackgroundColor(Color.TRANSPARENT)
        orientation = LinearLayout.HORIZONTAL
        gravity = Gravity.CENTER
        mLayoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        removeAllViews()
        imageViewList.clear()
        for (i in 0 until mSum) {
            val imageView = ImageView(mContext)
            imageViewList.add(imageView)
            addView(imageView)
        }
    }

    //设置圆点总数
    fun setLength(sum: Int) {
        this.mSum = sum
        init()
    }

    //设置选中圆点的下标
    fun setSelected(selected: Int) {
        this.mSelected = selected
        postInvalidate()
    }

    override fun onDraw(canvas: Canvas) {
        for (i in 0 until mSum) {
            val imageview = imageViewList[i]
            if (i == mSelected) {
                imageview.setImageDrawable(ContextCompat.getDrawable(mContext!!, indicatorRes[0]))
            } else {
                imageview.setImageDrawable(ContextCompat.getDrawable(mContext!!, indicatorRes[1]))
            }
            if (i < mSum - 1) {
                imageview.setPadding(0, 0, DensityUtils.dip2px(mContext!!, padding), 0)
            } else {
                imageview.setPadding(0, 0, 0, 0)
            }
            imageview.layoutParams = mLayoutParams
        }
    }
}